import { getDictList, getTitleDetl } from '@/api/commonApi';
const state = {
  areaMaps: new Map(), // 大区缓存
  cityMaps: new Map(), // 城市缓存
  storeMaps: new Map(), // 门店缓存
  dictFormula: [],
  dictMaps: new Map(),
  isFirst: true,
  breadTitle: ''
};
const mutations = {
  SET_AREA: (state, { str, data: val }) => {
    if (!state.areaMaps.has(str)) {
      state.areaMaps.set(str, val);
    }
  },
  SET_CITY: (state, { str, data: val }) => {
    if (!state.cityMaps.has(str)) {
      state.cityMaps.set(str, val);
    }
  },
  SET_STORE: (state, { str, data: val }) => {
    if (!state.storeMaps.has(str)) {
      state.storeMaps.set(str, val);
    }
  },
  // 设置全局缓存
  SET_FORMULA: (state, data) => {
    let n = data.length;
    while (n > 0) {
      n--;
      state.dictMaps.set(data[n].name, data[n].value);
    }
    state.dictFormula.push(data);
  },
  // 设置是否为第一次请求
  SET_ISFIRST: (state, flag) => {
    state.isFirst = flag;
  },
  SET_BREADTITLE: (state, flag) => {
    state.breadTitle = flag;
  }

};
const actions = {
  /* // 小组权限  start */
  intData({ commit }, key) {
    // console.log(key);
    const dataType = {
      SET_AREA: 'REGION_DICT',
      SET_CITY: 'CITY_DICT',
      SET_STORE: 'STORE_DICT'
    };
    const params = {
      reportType: 'BUSINESS_CATEGORY_REGION_CITY_SHOP',
      type: dataType[key]
    };
    return new Promise((resolve, reject) => {
      getDictList(params).then(({ data }) => {
        commit(key, { str: 'all', data });
        resolve();
      });
    });
  },
  async getData({ commit }, { key, str, param }) {
    const dataType = {
      'SET_AREA': 'REGION_DICT',
      'SET_CITY': 'CITY_DICT',
      'SET_STORE': 'STORE_DICT'
    };

    const params = {
      ...param,
      reportType: 'REGION_CITY_SHOP',
      type: dataType[key]
    };
    await new Promise((resolve, reject) => {
      return getDictList(params).then(({ data }) => {
        commit(key, { str, data });
        resolve(data);
      });
    });
  },
  /* // 小组权限  end */
  /* 所有表头公式详情 */
  async getFormulaList({ commit, state }) {
    if (state.isFirst && !state.dictFormula.length) {
      commit('SET_ISFIRST', false);
      await new Promise((resolve, reject) => {
        return getTitleDetl({
          'keys': []
        }).then(({ data }) => {
          commit('SET_ISFIRST', true);
          commit('SET_FORMULA', data);
          resolve();
        });
      });
    }
  }
};
export default {
  namespaced: true,
  state,
  mutations,
  actions
};
